package com.cristina.attention.server.handler;

import com.cristina.attention.dispatcher.MessageDispatcher;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author superman
 * @Date 2021/9/21 20:49
 **/
@Component
public class NettyServerHandlerInitializer extends ChannelInitializer<SocketChannel> {

    @Resource
    private NettyServerHandler nettyServerHandler;

    @Resource
    private MessageDispatcher messageDispatcher;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 60 秒没有向客户端发送消息就发生心跳
        pipeline.addLast(new IdleStateHandler(60, 0, 0))
                .addLast(new HttpServerCodec())
                .addLast(new HttpObjectAggregator(65536))
                .addLast(new ChunkedWriteHandler())
                .addLast(new WebSocketServerProtocolHandler("/websocket"))
                .addLast(messageDispatcher)
                .addLast(nettyServerHandler);
    }
}
